package ReflectionLearn.RefleDeepLearn;

import ReflectionLearn.RefleDeepLearnClass.Person;
import org.junit.jupiter.api.Test;


import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @author Lenl
 * @version v1.0
 * @create 2021-06-07 12:50
 * @description 获取运行时类的方法结构
 *
 *
 */
public class MethodTest {

    @Test
    public void test1(){
        Class clazz= Person.class;
        //getMethod能获取所继承的方法，getDeclaredMethods能获取当前运行时类的私有方法和公开方法
        Method[] methods=clazz.getDeclaredMethods();
        for (Method m:methods ){
            System.out.println(m.toString());
        }
    }

    /**
     * 权限修饰符 返回值类型 方法名(参数类型1，形参名1...) throws XxxException{}
     */
    @Test
    public void test2(){

        Class clazz= Person.class;
        Method[] methods=clazz.getDeclaredMethods();
        for (Method m:methods ){
            //1.获取方法声明的注解
            Annotation[] anno= m.getDeclaredAnnotations();
            for(Annotation an:anno){
                System.out.println(an);//获取注解需要注解的元注解Retention为Runtime
            }
            //2.获取权限修饰符
            System.out.print(Modifier.toString(m.getModifiers())+"\t");

            //3.获取方法返回值类型
            System.out.print(m.getReturnType().getName()+"\t");

            //4.方法名
            System.out.print(m.getName());

            System.out.print("(");
            //5.获取形参列表
            Class[] parameterTypes=m.getParameterTypes();
            if(!(parameterTypes==null||parameterTypes.length==0)){
                for (int i=0;i<parameterTypes.length;i++){
                    if(i==parameterTypes.length-1){
                        System.out.print(parameterTypes[i].getName()+" args_"+i);
                        break;
                    }
                    System.out.print(parameterTypes[i].getName()+" args_"+i+",");
                }
            }
            System.out.print(")");

            //6.抛出的异常
            Class[] exceptionTypes=m.getExceptionTypes();
            if(!(exceptionTypes==null||exceptionTypes.length==0)){
                System.out.print("throws ");
                for (int i=0;i<exceptionTypes.length;i++){
                    if(i==exceptionTypes.length-1){
                        System.out.print(exceptionTypes[i].getName());
                        break;
                    }
                    System.out.print(exceptionTypes[i].getName()+",");
                }
            }


            System.out.println();
        }
    }

}
